10 / 12

What happens if a Base class constructor throws an exception? Does the Derived object get created?

Difficulty: 4/10

Base Constructor Failure

If a base-class constructor throws an exception, construction of the derived object does not complete successfully. The derived constructor body is not reached because the base portion of the object must be initialized before the derived portion. The runtime propagates the exception according to the language's exception rules. From a design perspective, constructors should validate required state and establish invariants, but they should generally avoid complex external operations that can make object creation unpredictable.

javascript
  1. 1

    Base construction occurs before derived construction.

  2. 2

    If base construction fails, derived construction does not complete.

  3. 3

    The derived constructor body is not executed after a failed base construction.

  4. 4

    The object is not returned as a successfully constructed instance.

  5. 5

    Constructor failures should leave no usable partially initialized object exposed.

Follow-up Questions

  • In what order are constructors executed?
  • What happens if a derived constructor throws?
  • Can a constructor catch an exception from the base constructor?
  • Why should constructors avoid external I/O?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.